public class DeadLock {
    public static String r1="r1";
    public static String r2="r2";
    public static void main(String[] args) {
        Runable1 runable1=new Runable1();
        Runable2 runable2=new Runable2();
        Thread thread1=new Thread(runable1);
        Thread thread2=new Thread(runable2);
        thread1.start();
        thread2.start();
    }
}
class Runable1 implements Runnable{
    @Override
    public void run() {
        try {
            if (DeadLock.r1.hashCode()>DeadLock.r2.hashCode()) {
                synchronized (DeadLock.r1) {
                    System.out.println("Runable1的synchronized锁住r1");
                    Thread.sleep(3000);
                    synchronized (DeadLock.r2) {
                        System.out.println("Runable1的synchronized锁住r2");
                        Thread.sleep(3000);
                    }
                    System.out.println("解锁了，可以打印");
                }
            }else{
                synchronized (DeadLock.r2) {
                    System.out.println("Runable1的synchronized锁住r1");
                    Thread.sleep(3000);
                    synchronized (DeadLock.r1) {
                        System.out.println("Runable1的synchronized锁住r2");
                        Thread.sleep(3000);
                    }
                    System.out.println("解锁了，可以打印");
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
class Runable2 implements Runnable{
    @Override
    public void run() {
        try {
            if (DeadLock.r1.hashCode()<DeadLock.r2.hashCode()) {
                synchronized (DeadLock.r2) {
                    System.out.println("Runable2的synchronized锁住r2");
                    Thread.sleep(3000);
                    synchronized (DeadLock.r1) {
                        System.out.println("Runable2的synchronized锁住r1");
                        Thread.sleep(3000);
                    }
                    System.out.println("解锁了，可以打印");
                }
            }else{
                synchronized (DeadLock.r1) {
                    System.out.println("Runable2的synchronized锁住r1");
                    Thread.sleep(3000);
                    synchronized (DeadLock.r2) {
                        System.out.println("Runable2的synchronized锁住r2");
                        Thread.sleep(3000);
                    }
                    System.out.println("解锁了，可以打印");
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
